﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using BigDogSoft.Pages;
using BigDogSoft.Pages.forms;
using BigDogSoft.Utils;
using HslCommunication;
using HslCommunication.Core.Net;
using HslCommunication.Profinet.Siemens;
using HZH_Controls.Forms;
using Infrastructure;
using Infrastructure.DAL;
using Infrastructure.Models;

namespace BigDogSoft
{
    public partial class FrmMain :Form
    {

        private Control currentControl = null;
        public System.Threading.Timer threadTimer;
        /// <summary>
        /// UI主线程
        /// </summary>
        public static SynchronizationContext WindowUIContext { get; set; }
        /// <summary>
        /// 打开过的页面
        /// </summary>
        private Dictionary<string, Control> Pages = new Dictionary<string, Control>();
        public FrmMain()
        {
            InitializeComponent();
            this.FormClosed += FrmMain_FormClosed;
            WindowUIContext= SynchronizationContext.Current;
            threadTimer = new System.Threading.Timer(FetchData);
            threadTimer.Change(0, 1000);
            

        }



        #region  菜单
        private void 用户管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //CtrlUserManager ctl = new CtrlUserManager();
            //AddControl(ctl);
            AddControl<CtrlUserManager>();
            this.Text = "其然C#上位机软件V1.0" + "-用户管理";
        }

        private void AddControl(Control ctl)
        {
            if (this.currentControl==null||
                this.currentControl.GetType()!=ctl.GetType())
            {
                ctl.Dock = DockStyle.Fill;
                //ctl.Font = this.panelContainer.Font;
                this.panelContainer.Controls.Clear();
                this.panelContainer.Controls.Add(ctl);
                this.currentControl = ctl;
            }
        }

        private void 设备变量设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            //UtlDeviceVarSetting ctl = new UtlDeviceVarSetting();
            //AddControl(ctl);
            AddControl<UtlDeviceVarSetting>();
            this.Text = "其然C#上位机软件V1.0" + "-设备变量设置";
        }
        private void 监视变量管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //UtlVarMonitor ctl = new UtlVarMonitor();
            //AddControl(ctl);
            AddControl<UtlVarMonitor>();
            this.Text = "其然C#上位机软件V1.0" + "-监控变量";
        }
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FrmChangePwd frm = new FrmChangePwd();
            frm.ShowDialog();
        }
        private void 关于我们ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmAbout frm = new FrmAbout();
            frm.ShowDialog();
        }
        #endregion


        /// <summary>
        /// 退出应用程序退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void 历史数据查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //UtlHistoryQuery ctl = new UtlHistoryQuery();
            //AddControl(ctl);
            AddControl<UtlHistoryQuery>();
            this.Text = "其然C#上位机软件V1.0" + "-历史数据查询";
        }

        private void 配方管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //UtlFormulaMgr ctl = new UtlFormulaMgr();
            //AddControl(ctl);
            AddControl<UtlFormulaMgr>();
            this.Text = "其然C#上位机软件V1.0" + "-配方管理";
        }

        private void 配方模板设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //UtlFormulaTemplate ctl = new UtlFormulaTemplate();
            //AddControl(ctl);
            AddControl<UtlFormulaTemplate>();
            this.Text = "其然C#上位机软件V1.0" + "-配方模板设置";
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            this.DoubleBuffered = true;//打开双缓存
            AddControl<UtlWecome>();
            this.timerDateShow.Start();
            //注册报警处理
            VarAlert alert = new VarAlert();
            alert.Init();
        }

        private void AddControl<T>() where T :Control, new()
        {
            Type t = typeof(T);
            if (this.currentControl == null ||
               this.currentControl.GetType() != t)
            {
                string key = t.FullName;
                Control ctl = null;
                if(!Pages.TryGetValue(key, out ctl))
                {
                    //如果字典集合当中没有页面我们创建下
                    ctl = new T();
                    ctl.Dock = DockStyle.Fill;
                    Pages.Add(key, ctl);
                }
                this.panelContainer.Controls.Clear();
                this.panelContainer.Controls.Add(ctl);
                this.currentControl = ctl;
            }
        }
        /// <summary>
        /// 定时器事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fetchDataTimer_Tick(object sender, EventArgs e)
        {
            this.toolStriptDatetime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
        Random random = new Random(70);

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.threadTimer.Dispose();
        }

        /// <summary>
        /// 定时1秒执行任务
        /// </summary>
        /// <param name="state"></param>
        private void FetchData(object state)
        {
            var deviceList = DeviceVarDAL.GetDeviceListFromCache();
            foreach (var device in deviceList)
            {
                NetworkDeviceBase netClient = DeviceComminucationFactory.GetDeviceNetClient(device);
                if (netClient != null)
                {
                    var varList = DeviceVarDAL.GetDeviceVarListByDeviceIdFromCache(device.id);
                    foreach (var varItem in varList)
                    {
                        VarType vt;
                        Enum.TryParse<VarType>(varItem.var_type, out vt);
                       
                        switch (vt)
                        {
                            case VarType.Boolean:

                                OperateResult<bool> result = netClient.ReadBool(varItem.var_address);
                                if (result.IsSuccess) { varItem.var_val = result.Content.ToString(); }
                                break;
                            case VarType.Float:
                                OperateResult<float> result1 = netClient.ReadFloat(varItem.var_address);
                                if (result1.IsSuccess) { varItem.var_val = result1.Content.ToString(); }
                                break;
                            case VarType.Int16:
                                OperateResult<Int16> result2 = netClient.ReadInt16(varItem.var_address);
                                if (result2.IsSuccess) { varItem.var_val = result2.Content.ToString(); }
                                break;
                            case VarType.Int32:
                                OperateResult<Int32> result3 = netClient.ReadInt32(varItem.var_address);
                                if (result3.IsSuccess) { varItem.var_val = result3.Content.ToString(); }
                                break;
                            case VarType.UInt16:
                                OperateResult<UInt16> result4 = netClient.ReadUInt16(varItem.var_address);
                                if (result4.IsSuccess) { varItem.var_val = result4.Content.ToString(); }
                                break;
                            case VarType.UInt32:
                                OperateResult<UInt32> result5 = netClient.ReadUInt32(varItem.var_address);
                                if (result5.IsSuccess) { varItem.var_val = result5.Content.ToString(); }
                                break;
                        }

                        //varItem.var_val = random.Next(1000).ToString();
                        varItem.create_time = DateTime.Now;
                        //通知订阅者
                        EventBus.FireAll(varItem);
                    }
                    //保存到我们的数据库里
                    int row = DeviceVarDAL.SaveVarData(varList);
                }
            }
        }
    }
}
